package org.standard.commons.struts2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class BaseUploadAction extends BaseAction {
	
	public File[] annex;
	public String[] annexContentType;
	public String[] annexFileName;
	
	/**
	 * 上传文件
	 * @param savePath 文件保存根目录
	 * @return
	 * @throws IOException 
	 * @throws BaseException 抛出异常表示文件上传失败
	 */
	public String[][] uploadAndSave(String savePath) throws IOException{
		String[][] result = new String[0][0];
		if(annex != null){
			File file = new File(savePath);
			if(!file.exists()){
				file.mkdirs();
			}
			result = new String[annex.length][4];		//数组值：0文件原名，1文件保存在服务器上的名称，2文件大小，3文件类型
			FileOutputStream out = null;
			FileInputStream in = null;
			byte[] buff = new byte[10240];
			String fileType;
			String saveName;
			int length = 0;
			for(int i = 0;i < annex.length;i++){
				if(annexFileName[i].indexOf(".") != -1){
					fileType = annexFileName[i].substring(annexFileName[i].lastIndexOf(".") + 1);
				}else{
					fileType = "";
				}
				saveName = new Date().getTime() + "." + fileType;
				out = new FileOutputStream(savePath + File.separator + saveName);
				in = new FileInputStream(annex[i]);
				if(in != null){
					//排除上传的文件为新建、大小为0的文件
					while ((length = in.read(buff)) > 0) {
						out.write(buff, 0, length);
					}
					result[i][0] = annexFileName[i];									//真实的附件名称
					result[i][1] = saveName;											//服务器上面保存的名称
					result[i][2]=""+(annex[i].length());								//附件大小
					result[i][3] = fileType;											//附件类型
					in.close();
					out.close();
				}
			}
		}
		return result;
	}
	
	public File[] getAnnex() {
		return annex;
	}

	public void setAnnex(File[] annex) {
		this.annex = annex;
	}

	public String[] getAnnexContentType() {
		return annexContentType;
	}

	public void setAnnexContentType(String[] annexContentType) {
		this.annexContentType = annexContentType;
	}

	public String[] getAnnexFileName() {
		return annexFileName;
	}

	public void setAnnexFileName(String[] annexFileName) {
		this.annexFileName = annexFileName;
	}

}
